﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.Extend.Dtos.Employee;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 职员管理（导入导出）
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.12.01 
    /// </summary>
    [Route("api/Extend/Employee")]
    public class EmployeeController : BaseApiController
    {
        private EmployeeBll employeeBll = new EmployeeBll();

        #region GET
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] EmployeeListQuery input)
        {
            var pageInput = input.MapTo<PageInput>();
            pageInput.queryJson = new { input.condition }.ToJson();
            var data = await employeeBll.GetList(pageInput);
            var output = new PageResult() { list = data.list.MapToList<EmployeeListOutput>(), pagination = data.pagination };
            return Success(output);
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("Info/{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = await employeeBll.GetInfo(id);
            return Success(data);
        }
        #endregion

        #region POST
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        [HttpPost("Create")]
        public async Task<ResponseResult> Create(EmployeeEntity entity)
        {
            await employeeBll.Create(entity);
            return Success("新建成功");
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        [HttpPost("Update/{id}")]
        public async Task<ResponseResult> Update(string id, EmployeeEntity entity)
        {
            await employeeBll.Update(id, entity);
            return Success("更新成功");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await employeeBll.GetInfo(id);
            if (entity != null)
            {
                await employeeBll.Delete(entity);
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 导入预览
        /// </summary>
        /// <returns></returns>
        [HttpPost("ImportPreview")]
        public async Task<ResponseResult> ImportPreview()
        {
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var filePath = ConfigurationKey.TemporaryFilePath;
            var fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            var savePath = filePath + fileName;
            if (file.FileName == "employee_import_template.xlsx")
            {
                using (var stream = new FileStream(savePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                //得到数据
                var excelData = ExcelImportHelper.ToDataTable(savePath);
                //删除文件
                FileHelper.DeleteFile(savePath);
                //返回结果
                return Success(new
                {
                    columns = excelData.Columns,
                    dataRow = excelData,
                });
            }
            else
            {
                return Error("选择文件不符合导入");
            }
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="postParam">请求参数</param>
        /// <returns></returns>
        [HttpPost("ImportData")]
        public async Task<ResponseResult> ImportData()
        {
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var _filePath = ConfigurationKey.TemporaryFilePath;
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(_filePath + _fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            //得到数据
            var excelData = ExcelImportHelper.ToDataTable(_filePath + _fileName);
            employeeBll.ImportData(excelData);
            //删除文件
            FileHelper.DeleteFile(_filePath + _fileName);
            return Success("导入成功");
        }

        /// <summary>
        /// 模板下载
        /// </summary>
        [HttpGet("TemplateDownload")]
        public async Task<ResponseResult> TemplateDownload()
        {
            var userinfo = UserProvider.Instance.Get();
            var filePath = ConfigurationKey.TemplateFilePath + "employee_import_template.xlsx";//模板路径
            var addFilePath = ConfigurationKey.TemporaryFilePath + "职员信息模板.xlsx";//保存路径
            if (!FileHelper.IsExistFile(addFilePath))
            {
                List<ExcelTemplateModel> templateList = new List<ExcelTemplateModel>();
                ExcelExportHelper<ExcelTemplateModel>.Export(templateList, filePath, addFilePath);
            }
            return Success(new { name = "职员信息模板.xlsx", url = "/api/Common/Download?encryption=" + userinfo.Id + "|职员信息模板.xlsx" });
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        [HttpGet("ExportExcel")]
        public async Task<ResponseResult> ExportExcel()
        {
            var exportData = await employeeBll.GetList();
            var userinfo = UserProvider.Instance.Get();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "职员信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "EnCode", ExcelColumn = "工号" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "FullName", ExcelColumn = "姓名" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "Gender", ExcelColumn = "性别" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "DepartmentName", ExcelColumn = "部门" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "PositionName", ExcelColumn = "职位" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "WorkingNature", ExcelColumn = "用工性质" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "IDNumber", ExcelColumn = "身份证号" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "Telephone", ExcelColumn = "联系电话" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "Birthday", ExcelColumn = "出生年月" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "AttendWorkTime", ExcelColumn = "参加工作" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "Education", ExcelColumn = "最高学历" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "Major", ExcelColumn = "所学专业" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "GraduationAcademy", ExcelColumn = "毕业院校" });
            excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = "GraduationTime", ExcelColumn = "毕业时间" });
            var addPath = ConfigurationKey.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<EmployeeEntity>.Export(exportData, excelconfig, addPath);
            return Success(new { name = excelconfig.FileName, url = "/api/Common/Download?encryption=" + userinfo.Id + "|" + excelconfig.FileName });
        }

        /// <summary>
        /// 导出Word
        /// </summary>
        [HttpGet("ExportWord")]
        public async Task<ResponseResult> ExportWord()
        {
            var exportData = await employeeBll.GetList();
            var userinfo = UserProvider.Instance.Get();
            Dictionary<string, string> titles = new Dictionary<string, string>();
            titles.Add("FullName", "姓名");
            titles.Add("Gender", "性别");
            titles.Add("DepartmentName", "部门");
            titles.Add("PositionName", "职位");
            titles.Add("WorkingNature", "用工性质");
            titles.Add("IDNumber", "身份证号");
            titles.Add("Telephone", "联系电话");
            titles.Add("Birthday", "出生年月");
            titles.Add("AttendWorkTime", "参加工作");
            titles.Add("Education", "最高学历");
            titles.Add("Major", "所学专业");
            titles.Add("GraduationAcademy", "毕业院校");
            titles.Add("GraduationTime", "毕业时间");
            var fileName = "职员信息" + CommonHelper.Guid + ".doc";
            var addPath = ConfigurationKey.TemporaryFilePath + fileName;
            WordHelper.Export("职员信息", exportData, titles, addPath);
            return Success(new { name = fileName, url = "/api/Common/Download?encryption=" + userinfo.Id + "|" + fileName });
        }

        /// <summary>
        /// 导出PDF
        /// </summary>
        [HttpGet("ExportPdf")]
        public async Task<ResponseResult> ExportPdf()
        {
            var exportData = await employeeBll.GetList();
            var userinfo = UserProvider.Instance.Get();
            #region word
            Dictionary<string, string> titles = new Dictionary<string, string>();
            titles.Add("FullName", "姓名");
            titles.Add("Gender", "性别");
            titles.Add("DepartmentName", "部门");
            titles.Add("PositionName", "职位");
            titles.Add("WorkingNature", "用工性质");
            titles.Add("IDNumber", "身份证号");
            titles.Add("Telephone", "联系电话");
            titles.Add("Birthday", "出生年月");
            titles.Add("AttendWorkTime", "参加工作");
            titles.Add("Education", "最高学历");
            titles.Add("Major", "所学专业");
            titles.Add("GraduationAcademy", "毕业院校");
            titles.Add("GraduationTime", "毕业时间");
            var wordName = "职员信息" + DateTime.Now.ToString("yyyyMMdd") + ".doc";
            var addPath = ConfigurationKey.TemporaryFilePath + wordName;
            if (!FileHelper.IsExistFile(addPath))
            {
                WordHelper.Export(wordName, exportData, titles, addPath);
            }
            PDFHelper.AsposeWordToPDF(addPath);
            FileHelper.Delete(addPath);
            var downLoadFileName = "职员信息" + DateTime.Now.ToString("yyyyMMdd") + ".pdf";
            #endregion
            return Success(new { name = downLoadFileName, url = "/api/Common/Download?encryption=" + userinfo.Id + "|" + downLoadFileName });
        }
        #endregion
    }
}
